import os
import sys
from datetime import datetime

class ConsoleHandler:
    """Handle console output and optional file logging"""
    
    def __init__(self, output_file='result/analysis_results.txt'):
        self.output_file = output_file
        self.start_time = datetime.now()
        self._ensure_output_dir()
        
    def _ensure_output_dir(self):
        """Ensure output directory exists"""
        if self.output_file:
            os.makedirs(os.path.dirname(self.output_file), exist_ok=True)
        
    def log(self, message, print_to_console=True, save_to_file=True):
        """Log message to console and optionally to file"""
        if print_to_console:
            print(message)
        
        if save_to_file and self.output_file:
            timestamp = datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
            with open(self.output_file, 'a', encoding='utf-8') as f:
                f.write(f"{timestamp} {message}\n")
    
    def log_section(self, title, print_to_console=True):
        """Log a section header"""
        separator = "=" * 60
        self.log(separator, print_to_console)
        self.log(title, print_to_console)
        self.log(separator, print_to_console)
    
    def log_table(self, headers, rows, print_to_console=True):
        """Log a formatted table"""
        if not rows:
            return
            
        # Calculate column widths
        col_widths = [len(str(header)) for header in headers]
        for row in rows:
            for i, cell in enumerate(row):
                if i < len(col_widths):
                    col_widths[i] = max(col_widths[i], len(str(cell)))
        
        # Create format string
        format_str = "  ".join(f"{{:<{width}}}" for width in col_widths)
        
        # Log header
        self.log(format_str.format(*headers), print_to_console)
        self.log("-" * sum(col_widths + [2 * (len(headers) - 1)]), print_to_console)
        
        # Log rows
        for row in rows:
            # Pad row to match header length
            padded_row = row + [''] * (len(headers) - len(row))
            self.log(format_str.format(*padded_row), print_to_console)
    
    def log_progress(self, current, total, message="Processing"):
        """Log progress information"""
        if total > 0:
            percent = (current / total) * 100
            self.log(f"{message}: {current}/{total} ({percent:.1f}%)", print_to_console=True)
    
    def log_summary(self, total_files, processed_files, errors=0):
        """Log processing summary"""
        elapsed = datetime.now() - self.start_time
        self.log_section("处理汇总")
        self.log(f"总文件数: {total_files}")
        self.log(f"成功处理: {processed_files}")
        self.log(f"错误数: {errors}")
        self.log(f"处理时间: {elapsed.total_seconds():.2f} 秒")
        self.log(f"平均每个文件处理时间: {elapsed.total_seconds()/max(processed_files,1):.2f} 秒")
    
    def log_detailed_results(self, message):
        """Log detailed results to file only (not console)"""
        if self.output_file:
            with open(self.output_file, 'a', encoding='utf-8') as f:
                f.write(f"{message}\n")
    
    def clear_file(self):
        """Clear the output file"""
        if self.output_file:
            self._ensure_output_dir()
            with open(self.output_file, 'w', encoding='utf-8') as f:
                f.write("")  # Clear the file content

# Global console handler instance
console = ConsoleHandler()
